package com.sky.service.admin.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.DataException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.admin.EmployeeMapper;
import com.sky.pojo.Employee;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.admin.EmployeeService;
import com.sky.vo.EmployeeVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.nio.charset.Charset;

@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = true)
public class EmployeeServiceImpl  implements EmployeeService {

    @Resource
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();//

        //1、根据用户名查询数据库中的数据  select * from employee where username = #{username}
        Employee employee = employeeMapper.getByUsername(username); //

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        password = DigestUtils.md5DigestAsHex(password.getBytes(Charset.forName("UTF-8")));
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     *
     * @param dto 前端传递的参数
     * @return
     */
    @Override
    @Transactional(readOnly = false)
    public Result<String> save(EmployeeDTO dto) {
        //1. 判断dto是否有数据 如果没有数据则抛出异常
        if(null == dto || StringUtils.isEmpty(dto.getIdNumber()) || StringUtils.isEmpty(dto.getUsername())){
            throw new DataException(MessageConstant.DATA_ERROR);
        }

        //1.1 先查询一下当前的用户名是否使用过 如果已经使用过了则抛出异常 如果没有使用过则继续执行
        Employee emp = employeeMapper.getByUsername(dto.getUsername());
        if(null != emp){
            throw new DataException(dto.getUsername() + "已经存在请重新换一个名字");
        }

        //2. 创建pojo对象 并拷贝dto的数据到pojo
        Employee employee = new Employee();
        BeanUtils.copyProperties(dto, employee);

        //3. 对未拷贝成功的数据进行赋值
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes(Charset.forName("UTF-8"))));
        employee.setStatus(StatusConstant.ENABLE);
       /* employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        employee.setUpdateUser(BaseContext.getCurrentId());
        employee.setCreateUser(BaseContext.getCurrentId());*/

        //4. 调用mapper接口完成数据的新增
        employeeMapper.save(employee);

        //5. 返回结果
        return Result.success();
    }

    /**
     * 分页查询员工信息
     *
     * @param queryDTO
     * @return
     */
    @Override
    public Result<PageResult> queryPage(EmployeePageQueryDTO queryDTO) {
        //0. 建议执行查询条件之前先校验一下数据
        if(null == queryDTO){
            throw new DataException(MessageConstant.DATA_ERROR);
        }

        if(queryDTO.getPage() < 0 || queryDTO.getPage() > 100){
            queryDTO.setPage(1);
        }

        //1. 通过PageHelper设置分页参数
        PageHelper.startPage(queryDTO.getPage(), queryDTO.getPageSize());

        //2. 调用mapper接口完成条件查询(动态sql)
        Page<Employee> page = employeeMapper.selectPage(queryDTO.getName());

        //3. 封装返回的结果并返回
        //PageResult<Employee> pageResult = PageResult.builder().total(page.getTotal()).records(page.getResult()).build();
        PageResult<Employee> pageResult = new PageResult<>();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(page.getResult());

        return Result.success(pageResult);
    }

    /**
     * 禁用启用员工账号
     *
     * @param status 员工的状态
     * @param empId  员工的id
     * @return
     */
    @Override
    @Transactional(readOnly = false)
    public Result<String> startOrStop(Integer status, Long empId) {
        //count 存储的是这个sql影响的行数
        int count = employeeMapper.startOrStop(status, empId);
        return count == 1 ? Result.success():Result.error("更新失败");
    }

    /**
     * 根据id查询员工共
     *
     * @param id
     * @return
     */
    @Override
    public Result<EmployeeVO> selectById(Long id) throws CloneNotSupportedException {
        Employee employee = employeeMapper.selectById(id);
        EmployeeVO vo = employee.clone();

        return Result.success(vo);
    }

    /**
     * 根据id更新员工的信息
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(readOnly = false)
    public Result<String> updateById(EmployeeDTO dto) throws CloneNotSupportedException {
        Employee employee = dto.clone();
        //employee.setUpdateUser(BaseContext.getCurrentId());

        //count存储的是更新的sql影响的行数
        int count = employeeMapper.updateById(employee);
        return count == 1 ? Result.success():Result.error("更新失败");
    }


}
